package com.cershy.linyuminiserver.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class TimeRecordAspect {

    // 环绕通知，拦截被 @TimeRecord 注解标记的方法
    @Around("@annotation(com.cershy.linyuminiserver.annotation.TimeRecord)")
    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录方法开始执行的时间
        long startTime = System.currentTimeMillis();

        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            return result;
        } finally {
            // 记录方法结束执行的时间
            long endTime = System.currentTimeMillis();
            // 计算方法执行的耗时
            long duration = endTime - startTime;

            // 获取方法签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            // 输出方法名和耗时信息
            System.out.println("方法 " + method.getName() + " 执行耗时: " + duration + " 毫秒");
        }
    }
}